<template>
  <div class="h100 order">
    <v-tree @getOrgId="getOrgId" :params="dParams" api="depart.get_depart_count">
      <el-button
        type="default"
        icon="el-icon-refresh-right"
        class="ml10 pd10"
        slot="search"
        title="同步"
        :loading="syncLoading"
        @click="update"
      ></el-button>
      <span slot="content" ref="curID" class="content" slot-scope="curNum">
        <div class="count">
          <div class="countAll">
            <div class="title f14 font-gray">总金额</div>
            <div class="value f14 font-org fb">
              <v-countto :count="amounts.total_amount"></v-countto>&nbsp;
              <span class="f14 font-gray">元</span>
            </div>
          </div>
          <div class="statistic w100p">
            <div>
              <div class="title f14 font-gray">
                ECS (
                <span class="font-blue">{{curNum.data.aliyun_ecs_count_num_total || '-'}}</span>
                )
              </div>
              <div class="value f14 font-org fb nowrap">
                <v-countto :count="amounts.ecs_amount"></v-countto>&nbsp;
                <span class="f14 font-gray">元</span>
              </div>
            </div>
            <div>
              <div class="title f14 font-gray">
                RDS (
                <span class="font-blue">{{ curNum.data.aliyun_rds_count_num_total || '0' }}</span>
                )
              </div>
              <div class="value f14 font-org fb nowrap">
                <v-countto :count="amounts.rds_amount"></v-countto>&nbsp;
                <span class="f14 font-gray">元</span>
              </div>
            </div>
            <div>
              <div class="title f14 font-gray">
                OSS (
                <span class="font-blue">{{ curNum.data.aliyun_oss_count_num_total || '0' }}</span>
                )
              </div>
              <div class="value f14 font-org fb nowrap">
                <v-countto :count="amounts.oss_amount"></v-countto>&nbsp;
                <span class="f14 font-gray">元</span>
              </div>
            </div>
            <div>
              <div class="title f14 font-gray">
                SLB (
                <span class="font-blue">{{ curNum.data.aliyun_slb_count_num_total || '0' }}</span>
                )
              </div>
              <div class="value f14 font-org fb nowrap">
                <v-countto :count="amounts.slb_amount"></v-countto>&nbsp;
                <span class="f14 font-gray">元</span>
              </div>
            </div>
            <div>
              <div class="title f14 font-gray">
                REDIS (
                <span class="font-blue">{{ curNum.data.aliyun_redis_count_num_total || '0' }}</span>
                )
              </div>
              <div class="value f14 font-org fb nowrap">
                <v-countto :count="amounts.redis_amount"></v-countto>&nbsp;
                <span class="f14 font-gray">元</span>
              </div>
            </div>
          </div>
        </div>
        <div class="tabHead">
          <el-tabs v-model="order_type" @tab-click="getList">
            <el-tab-pane name="ECS" label="ecs">
              <span slot="label">
                &nbsp;
                <i class="el-icon-cloudy"></i> ECS &nbsp;
              </span>
            </el-tab-pane>
            <el-tab-pane name="RDS" label="rds">
              <span slot="label">
                &nbsp;
                <i class="el-icon-coin"></i> RDS &nbsp;
              </span>
            </el-tab-pane>
            <el-tab-pane name="OSS" label="oss">
              <span slot="label">
                &nbsp;
                <i class="el-icon-box"></i> OSS &nbsp;
              </span>
            </el-tab-pane>
            <el-tab-pane name="SLB" label="slb">
              <span slot="label">
                &nbsp;
                <i class="el-icon-cpu"></i> SLB&nbsp;
              </span>
            </el-tab-pane>
            <el-tab-pane name="REDIS" label="redis">
              <span slot="label">
                &nbsp;
                <i class="el-icon-collection"></i> REDIS&nbsp;
              </span>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="tab-content">
          <div class="listbox">
            <v-list
              v-if="params.department"
              :api="api.getUrl"
              ref="list"
              :cols="tableList[order_type].cols"
              :params="params"
            >
              <template slot="search">
                <el-date-picker
                  v-model="dateVal"
                  class="w250 verticalB"
                  size="small"
                  type="daterange"
                  align="right"
                  unlink-panels
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                  :picker-options="pickerOptions"
                  @change="setDate"
                ></el-date-picker>
                <el-select
                  size="small"
                  placeholder="版本"
                  class="w120 fr"
                  v-model="params.version"
                  :disabled="!$api.purview('order.get_all_goods_price_version')"
                >
                  <el-option
                    v-for="(val, inx) in config.goods_price_version"
                    :key="inx"
                    :label="val.name"
                    :value="val.key"
                  ></el-option>
                </el-select>
              </template>
              <template slot="head">
                <thead>
                  <th v-for="(item, inx) in tableList[order_type].item" :key="inx">{{ item }}</th>
                </thead>
              </template>
              <template slot="item" slot-scope="props">
                <tr :class="props.item.instance_id === activeInstance ? 'activeTr':''">
                  <td v-for="(item, key, inx) in tableList[order_type].item" :key="inx">
                    <!-- 1、实例有的需要和id一起展示，且实例变量不同
                    2、ip和CPU、内存一起展示，需特殊处理-->
                    <template
                      v-if="key === 'instance_name' || key === 'DBInstanceDescription' || key === 'instance_id' || key === 'LoadBalancerName' || key === 'InstanceName'"
                    >
                      <span
                        @click="rowInfo(props.item)"
                        class="font-blue cursor-pointer"
                      >{{ props.item[key] }}</span>
                      <template v-if="key !== 'instance_id'">
                        <br />
                        <span>{{ props.item.instance_id || '-' }}</span>
                      </template>
                    </template>
                    <template v-else-if="key === 'cpu' || key === 'DBInstanceCPU'">
                      <span>
                        <span class="font-red">{{ props.item[key] }}</span>核
                      </span>
                      <span>
                        <span
                          class="font-red"
                        >{{ props.item.memory || props.item.DBInstanceMemory || '-' }}</span>G
                      </span>
                    </template>
                    <!-- 账单状态 -->
                    <template v-else-if="key === 'indel'">
                      <span v-if="props.item[key] === 0" class="font-green">正常</span>
                      <span v-else-if="props.item[key] === 1" class="font-red">已删除</span>
                      <span v-else>-</span>
                    </template>
                    <!-- 金额 | thousandSeparate -->
                    <template
                      v-else-if="key.indexOf('amount') !== -1"
                    >{{ props.item[key] | thousandSeparate}} 元</template>
                    <template v-else>{{ props.item[key] }}</template>
                  </td>
                </tr>
              </template>
            </v-list>
          </div>
        </div>
      </span>
    </v-tree>
    <!-- 详情开始 -->
    <v-baseinfob v-model="drawer.show" :name="drawer.name">
      <template slot="operateIcon">
        <i
          v-if="!drawer.scale"
          class="el-icon-full-screen"
          style="right:60px;"
          ref="fullScreen"
          title="放大"
          @click="setTop"
        ></i>
        <i
          v-else
          class="el-icon-full-screen"
          style="right:60px;"
          ref="fullScreen"
          title="缩小"
          @click="setTop"
        ></i>
      </template>
      <div slot="content" class="wrapper-content drawer" v-loading="drawer.loading">
        <v-list
          :dataList="drawer.data"
          :hideTool="true"
          :cols="tableList[order_type].drawerCols"
          v-if="drawer.data.length"
        >
          <template slot="head">
            <thead>
              <th
                v-for="(item, key, inx) in tableList[order_type].drawerHeader"
                :key="inx"
              >{{ item }}</th>
              <th>天数</th>
              <th>金额</th>
              <th>开始时间</th>
              <th>结束时间</th>
            </thead>
          </template>
          <template slot="item" slot-scope="props">
            <tr>
              <td v-for="(item, key, inx) in tableList[order_type].drawerHeader" :key="inx">
                <!-- 实例|ID -->
                <template
                  v-if="key === 'instance_name' || key === 'DBInstanceDescription' || key === 'instance_id' || key === 'LoadBalancerName' || key === 'InstanceName'"
                >
                  <span class="font-blue">{{ props.item[key] }}</span>
                  <template v-if="key !== 'instance_id'">
                    <br />
                    <span>{{ props.item.instance_id || '-' }}</span>
                  </template>
                </template>
                <!-- ip|内存|CPU -->
                <template v-else-if="key === 'ip_address' || key === 'cpu'">
                  <template v-if="key !== 'cpu'">
                    <span>{{ props.item[key] || '-'}}</span>
                    <br />
                    <span>{{ props.item.eip_address || '-' }}(弹)</span>
                    <br />
                  </template>
                  <span>
                    <span class="font-red">{{ props.item.cpu }}</span>核
                  </span>
                  <span>
                    <span class="font-red">{{ props.item.memory }}</span>G
                  </span>
                </template>
                <!-- 金额 | thousandSeparate -->
                <template
                  v-else-if="key.indexOf('amount') !== -1 && key !== 'amount'"
                >{{ props.item[key] | thousandSeparate}} 元</template>
                <template v-else>
                  <span>{{props.item[key] }}</span>
                </template>
              </td>
              <td class="font-org">{{ props.item.days }}</td>
              <td class="font-red">{{ props.item.amount | thousandSeparate}} 元</td>
              <td>{{ props.item.start_time | dateFormat('yyyy-MM-dd') }}</td>
              <td>{{ props.item.end_time | dateFormat('yyyy-MM-dd') }}</td>
            </tr>
          </template>
        </v-list>
      </div>
    </v-baseinfob>
    <!-- 详情结束 -->
  </div>
</template>

<script>
import { cacheConfig } from "@cache";
export default {
  data() {
    return {
      params: {
        department: "",
        version: "",
        start: "",
        end: ""
      },
      tableList: {
        ECS: {
          item: {
            instance_name: "实例|ID",
            instance_type: "实例规格",
            department_name: "组织名称",
            cpu: "CPU|内存",
            indel: "账单状态",
            total_day: "总天数",
            total_type_amount: "实例金额",
            total_disk_hd_amount: "高效云盘金额",
            total_disk_ssd_amount: "SSD云盘金额",
            total_amount: "总金额"
          },
          cols: "0,0,0,100,80,80,110,110,100,110",
          drawerHeader: {
            instance_name: "实例|ID",
            ip_address: "IP|弹性IP|CPU|内存",
            disk_hd: "高效云盘大小(G)",
            disk_ssd: "SSD云盘大小(G)",
            type_amount: "实例金额",
            disk_hd_amount: "高效云盘金额",
            disk_ssd_amount: "SSD云盘金额"
          },
          drawerCols: ""
        },
        RDS: {
          item: {
            DBInstanceDescription: "实例|ID",
            DBInstanceClass: "实例规格",
            department_name: "组织名称",
            DBInstanceCPU: "CPU|内存",
            indel: "账单状态",
            total_day: "总天数",
            total_type_amount: "实例金额",
            total_disk_amount: "本地存储金额",
            total_amount: "总金额"
          },
          cols: "0,0,0,100,80,80,110,110,110",
          drawerHeader: {
            DBInstanceDescription: "实例|ID",
            cpu: "CPU|内存",
            type_amount: "实例金额",
            disk: "存储空间(G)",
            disk_amount: "本地存储金额"
          },
          drawerCols: ""
        },
        OSS: {
          item: {
            instance_id: "实例ID",
            StorageCapacity: "存储空间(G)",
            StorageClass: "存储类型",
            department_name: "组织名称",
            indel: "账单状态",
            total_day: "总天数",
            total_amount: "总金额"
          },
          cols: "0,0,0,0,100,100,110",
          drawerHeader: { instance_id: "实例ID", disk: "存储空间(G)" },
          drawerCols: ""
        },
        SLB: {
          item: {
            LoadBalancerName: "实例|ID",
            LoadBalancerSpec: "规格",
            Address: "IP",
            department_name: "组织名称",
            indel: "账单状态",
            total_day: "总天数",
            total_amount: "总金额"
          },
          cols: "0,0,0,0,100,100,110",
          drawerHeader: { LoadBalancerName: "实例ID" },
          drawerCols: ""
        },
        REDIS: {
          item: {
            InstanceName: "实例|ID",
            InstanceClass: "实例规格",
            department_name: "组织名称",
            indel: "账单状态",
            Capacity: "存储空间(G)",
            total_day: "总天数",
            total_amount: "总金额"
          },
          cols: "0,0,0,0,100,100,110",
          drawerHeader: {
            InstanceName: "实例|ID",
            capacity: "存储空间(G)",
            PrivateIp: "IP"
          },
          drawerCols: ""
        }
      },
      activeInstance: "", // 用于确定目前查看详情的tr项
      order_type: "ECS",
      dParams: {
        order_by: ""
      },
      api: {
        getUrl: "order.get_ecs_order_list",
        syncUrl: "order.sync_goods_update"
      },
      syncLoading: false,
      config: {},
      dateVal: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "默认",
            onClick(picker) {
              picker.$emit("pick", ["", ""]);
            }
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      drawer: {
        show: false,
        name: "账单",
        data: [],
        loading: false,
        scale: false
      },
      amounts: {
        ecs_amount: {},
        oss_amount: {},
        rds_amount: {},
        redis_amount: {},
        slb_amount: {},
        total_amount: {}
      },
      fromCahce: {}
    };
  },
  watch: {
    "drawer.show": {
      handler(val) {
        if (!val) {
          this.activeInstance = "";
          // 初始化下弹窗遮掩列表问题
          document.getElementsByClassName("right")[0].classList.remove("h55");
        }
      }
    },
    params: {
      handler(val) {
        if (val.department) {
          this.getCount();
        }
      },
      deep: true
    }
  },
  methods: {
    getCount() {
      let params = {};
      params = JSON.parse(JSON.stringify(this.params));
      let items = Object.keys(this.tableList);
      items.forEach(el => {
        let key = el.toLowerCase();
        params["is_" + key] = 1;
      });
      this.$api.jget("order.get_order_count", params).then(res => {
        if (res.status === 1 && res.data) {
          // count组件赋值
          for (const key in res.data) {
            this.amounts[key] = {};
            this.$set(this.amounts[key], "from", this.fromCahce[key] || 0);
            this.$set(
              this.amounts[key],
              "to",
              res.data[key].total_amount || res.data[key] || 0
            );
            this.fromCahce[key] =
              res.data[key].total_amount || res.data[key] || 0;
          }
        } else {
          this.$error(res.msg);
        }
      });
    },
    // 获取左侧组织id
    getOrgId(val) {
      if (this.params.department !== val) {
        this.params.department = val;
      }
    },
    // 同步
    update() {
      this.syncLoading = true;
      this.$api.jget(this.api.syncUrl).then(res => {
        if (res.status === 1) {
          this.$success(res.msg);
          this.$refs.list.fetchData();
        } else {
          this.$error(res.msg);
        }
        this.syncLoading = false;
      });
    },
    getList(val) {
      this.drawer.show = false;
      this.api.getUrl = `order.get_${val.label}_order_list`;
      this.dParams.order_by = `aliyun_${val.label}`;
    },
    setDate(date) {
      this.params.start = date[0];
      this.params.end = date[1];
    },
    rowInfo(item) {
      // 用于下弹窗遮掩列表问题
      document.getElementsByClassName("right")[0].classList.add("h55");
      this.activeInstance = item.instance_id;
      this.drawer.show = true;
      this.drawer.loading = true;
      this.drawer.data = [];
      let params = {
        instance_id: item.instance_id,
        start: this.params.start,
        end: this.params.end,
        version: this.params.version
      };
      this.$api
        .jget(`order.get_${this.order_type.toLowerCase()}_order_detail`, params)
        .then(res => {
          if (res.status === 1) {
            this.drawer.data = res.data.list;
          }
          this.drawer.loading = false;
        });
    },
    setTop() {
      this.drawer.scale = !this.drawer.scale;
      this.$refs.fullScreen.offsetParent.offsetParent.style.top = this.drawer
        .scale
        ? "0"
        : "55%";
    }
  },
  mounted() {
    this.config = cacheConfig.load();
    this.dParams.order_by = "aliyun_ecs";
    this.params.version = this.config.goods_price_version[0].key;
  }
};
</script>

<style lang="scss" scoped>
.count {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  & > div.countAll {
    border: 1px solid #efefef;
    border-right: 0;
    padding: 10px 10px 5px 10px;
    text-align: center;
    white-space: nowrap;
    background-color: #efefef;
    .value {
      margin: 5px 0;
    }
  }
}
.statistic {
  border: 1px solid #efefef;
  display: flex;
  justify-content: space-around;
  align-items: center;
  & > div {
    text-align: center;
    padding: 10px 10px 5px 10px;
    .value {
      margin: 5px 0;
    }
  }
}
.content {
  display: inline-block;
  min-width: 760px;
  width: 100%;
}
table.table td {
  word-break: break-all;
}
table.table th {
  white-space: nowrap;
}
table.table tr td:nth-last-child(1) {
  color: red;
}
.order .drawer {
  table.table th,
  table.table td {
    background-color: #fff;
    border: 1px solid #efefef;
  }
  table.table td {
    padding: 10px 13px;
  }
}
.activeTr {
  background-image: linear-gradient(
    30deg,
    rgba(0, 30, 98, 0.2),
    rgba(0, 0, 88, 0.07),
    rgba(0, 0, 88, 0)
  );
  & > td {
    background-color: unset !important;
  }
}
</style>